/*
 *      Filename: binary_search.c
 *       Version: 0.1.0
 *   Description: 给定数组 {-4, 1, 2, 2, 5, 5, 5, 8, 10}, 
 *                使用二分查找， 找到 小于等于 t的最后一个数, 
 *                假定t = 6.
 *
 *        Author: wuyaowei
 *          Date: 2020-08-01
 *
 */

#include <stdio.h>

static int a[] = {-4, 1, 2, 2, 5, 5, 5, 8, 10};
int search(int t) {
    int len = sizeof(a)/sizeof(int);
    int left = 0, right = len-1, mid = len >> 1;
    
    while(left <= right) {
	mid = left + ((right-left) >> 1);

        if((a[mid] <= t) && a[mid+1] > t) return mid;

	if(a[mid] > t) {
	    right = mid -1;
	} else {
	   left = mid +1;
	}
    }
}

void main() {
    int val = search(6);
    printf("小于等于t(6)的最后一个数是a[%d]:%d\n", val, a[val]);   
}
